<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span v-if="flowType == 1">{{ $route.query.type == "add" ? '新建基层理论宣讲集体申报' : "编辑基层理论宣讲集体申报" }}</span>
        <span v-else-if="flowType == 2">{{ $route.query.type == "add" ? '新建基层理论宣讲个人申报' : "编辑基层理论宣讲个人申报" }}</span>
        <span v-else-if="flowType == 3">{{ $route.query.type == "add" ? '新建优秀理论宣讲报告' : "编辑优秀理论宣讲报告" }}</span>
        <span v-else-if="flowType == 4">{{ $route.query.type == "add" ? '新建优秀理论宣讲微视频申报' : "编辑优秀理论宣讲微视频申报" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="180px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="事迹材料（文字）" prop="factualMaterials" v-if="flowType == 1 || flowType == 2">
          <el-input v-model="ruleForm.factualMaterials" placeholder="请输入事迹材料（文字）" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="宣讲报告（文字）" prop="report" v-if="flowType == 3">
          <el-input v-model="ruleForm.report" placeholder="请输入宣讲报告（文字）" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="宣传情况简介（文字）" prop="briefing"  v-if="flowType == 3" :rules="[{ required: true, message: '请输入宣讲情况简介', trigger: 'blur' },{ max: 255, message: '不能输入超过255个字符', trigger: 'blur'}]">
          <el-input v-model="ruleForm.briefing" placeholder="请输入宣传情况简介" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="报刊宣传" prop="promotionSituation" v-if="flowType != 4">
          <el-input v-model="ruleForm.promotionSituation" placeholder="请输入报刊宣传" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="获奖情况" prop="awards" v-if="flowType == 1 || flowType == 2">
          <el-input v-model="ruleForm.awards" placeholder="请输入获奖情况" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="微视频" prop="microVideo" v-if="flowType == 4">
          <video
            ref="videoRef"
            :src="videoUrl ? videoUrl : ''"
            :width="313"
            :height="170"
            muted
            controls
            loop
            showPlay
            controlslist="nodownload"
          ></video>
        </el-form-item>

        <el-form-item v-if="flowType == 4">
          <el-button type="primary" @click="uploadVideo">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传微视频
          </el-button>
          <span style="margin-left: 10px;">请上传不超过40M的视频文件，格式：mp4</span>
        </el-form-item>

        <el-form-item label="图片" prop="picture">
          <el-image style="width: 313px;"
            :src="imageUrl ? imageUrl : ''" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-image style="width: 313px;" src="/images/course_default.png" fit="cover" />
              </div>
            </template>
          </el-image>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadPicture">
            <el-icon>
              <UploadFilled />
            </el-icon>
            
            <span> {{ flowType == 4 ? '上传报道传播截图' : '上传图片' }}</span>
          </el-button>
          <span style="margin-left: 10px;">请上传不超过10M的图片，格式：jpg/png/jpeg</span>
        </el-form-item>

        <el-form-item label="视频" prop="video" v-if="flowType != 3 && flowType != 4">
          <video
            ref="videoRef"
            :src="videoUrl ? videoUrl : ''"
            :width="313"
            :height="170"
            muted
            controls
            loop
            showPlay
            controlslist="nodownload"
          ></video>
        </el-form-item>

        <el-form-item v-if="flowType != 3 && flowType != 4">
          <el-button type="primary" @click="uploadVideo">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传视频
          </el-button>
          <span style="margin-left: 10px;">请上传视频文件，格式：mp4</span>
        </el-form-item>

        <el-form-item label="视频创作传播相关情况说明" prop="briefing" v-if="flowType == 4" :rules="[{ required: true, message: '请填写视频创作传播相关情况说明', trigger: 'blur' },{ max: 255, message: '不能输入超过255个字符', trigger: 'blur'}]">
          <el-input v-model="ruleForm.briefing" placeholder="请输入视频创作传播相关情况说明" autosize type="textarea"></el-input>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCollectivenessAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { UploadFilled, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const router = useRouter()
const route = useRoute()

const flowType = computed(() => {
  const current = route.path.replace(/\/backend/g, '')
  // 宣讲集体
  if (current == '/publicize-collectiveness/add') return 1
  // 先进个人
  if (current == '/publicize-personal/add') return 2
  // 优秀理论宣讲报告
  if (current == '/publicize-report/add') return 3
  // 优秀理论宣讲微视频
  if (current == '/publicize-video/add') return 4
  return ''
})

onMounted(() => {
  if(route.query.id){
    getCollectivenessDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getCollectivenessDetail = () => {
  loading.value = true
  http.$GET("/PreachM/GetPreachFillingDetailById", { Id: route.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return
    
    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 图片路径 */
    if(!isJsonString(res.result.picture)){
      imageUrl.value = ""
      ruleForm.value.picture = ""
      return
    }
    if(res.result.picture != ''){
      let picture = JSON.parse(res.result.picture)

      if(picture.filePathArray){
        imageUrl.value = import.meta.env.VITE_APP_STATIC_URL + picture.filePathArray[0].CompleteFilePath
      }else{
        imageUrl.value = ""
        ruleForm.value.picture = ""
      }
    }

    if(!isJsonString(res.result.video)){
      videoUrl.value = ""
      ruleForm.value.video = ""
      return
    }
    /* 视频路径 */
    if(res.result.video != ''){
      let video = JSON.parse(res.result.video)

      if(video.filePathArray){
        videoUrl.value = import.meta.env.VITE_APP_STATIC_URL + video.filePathArray[0].CompleteFilePath
      }else{
        videoUrl.value = ""
        ruleForm.value.video = ""
      }
    }
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: "",
  fillingType: flowType.value,
  fillingTypeName: flowType.value == 1 ? "基层理论先进宣讲集体" : flowType.value == 2 ? "基层理论宣讲先进个人" : flowType.value == 3 ? "优秀理论宣讲报告" : flowType.value == 4 ? "优秀理论宣讲微视频" : "" ,
  factualMaterials: "",
  promotionSituation: "",
  awards: "",
  picture: "",
  video: "",
  report: "",
  briefing: "",
  microVideo: "",
})

/* 图片路径 */
const imageUrl = ref(null)
/* 是否有上传图片 */
const isUploadImage = ref(false)
/* 图片校验规则 */
const checkImage = (rule, value, callback) => {
  if (!ruleForm.value.picture) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}

/* 视频路径 */
const videoUrl = ref(null)
/* 是否有上传视频 */
const isUploadVideo = ref(false)
/* 视频校验规则 */
const checkVideo = (rule, value, callback) => {
  if (!ruleForm.value.video) {
    callback(new Error('请上传视频'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  factualMaterials: [
    { required: true, message: '请输入事迹材料（文字）', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  promotionSituation: [
    { required: true, message: '请输入报刊宣传', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  awards: [
    { required: true, message: '请输入获奖情况', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  report: [
    { required: true, message: '请输入宣讲报告', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  microVideo: [
    { required: true, validator: checkVideo, message: '请上传微视频', trigger: 'change' }
  ],
  /* picture: [
    { required: true, validator: checkImage, message: '请上传封面图片', trigger: 'change' }
  ],
  video: [
    { required: true, validator: checkVideo, message: '请上传视频', trigger: 'change' }
  ], */
})

/* 点击上传图片 */
const uploadPicture = () => {

  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG)$/)){
      ruleForm.value.picture = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }
    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.picture = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadImage.value = true
      ruleForm.value.picture = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('picture')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 点击上传视频 */
const uploadVideo = () => {

  /* 文件上传类型 */
  let fileType = ".mp4,.MP4"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(mp4|MP4)$/)){
      ruleForm.value.video = ""
      videoUrl.value = ""
      isUploadVideo.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadVideo.value = true
      ruleForm.value.video = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('video')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        videoUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if(!isUploadImage.value) {
        delete ruleForm.value.picture
      }

      /* 未更新视频时不传值 */
      if(!isUploadVideo.value) {
        delete ruleForm.value.video
      }

      http.$POST("/PreachM/AddOrUpdatePreachFilling", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');

          let url;
          // 宣讲集体
          if (flowType.value == 1) url = '/backend/publicize-collectiveness'
          // 先进个人
          if (flowType.value == 2) url = '/backend/publicize-personal'
          // 优秀理论宣讲报告
          if (flowType.value == 3) url = '/backend/publicize-report'
          // 优秀理论宣讲微视频
          if (flowType.value == 4) url = '/backend/publicize-video'

          router.push({
            path: url
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ""
  isUploadImage.value = false
  videoUrl.value = ""
  isUploadVideo.value = false
}

/* 返回列表 */
const goList = () => {
  let url;
  // 宣讲集体
  if (flowType.value == 1) url = '/backend/publicize-collectiveness'
  // 先进个人
  if (flowType.value == 2) url = '/backend/publicize-personal'
  // 优秀理论宣讲报告
  if (flowType.value == 3) url = '/backend/publicize-report'
  // 优秀理论宣讲微视频
  if (flowType.value == 4) url = '/backend/publicize-video'

  router.push({
    path: url,
    query: route.query.currentPage ? { currentPage: route.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>